import * as types from './types'
import $http from '../../utils/http'
import { Notification } from 'atelement'
import { TableArgs } from './utils/config.js'

/**
   * @description 获取脆弱性风险 统计信息
   * @param {websiteId} String - 网站编号
   * @param {riskId} String - 风险编号
   * @param {isValidateInit} Object - 当前告警在最新批次中是否进行过验证、处置信息初始化
  */
const actions = {
  /**
   * @description 自动分析--获取攻击事件 统计信息
  */
  [types.GET_ATTACK_STATISTICAL] ({ commit, state }) {
    $http.get('/api/analyze/autoAnalyze/getAttackStatistical').then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_ATTACK_STATISTICAL, { data: data.dataSource, type: 'AutoAttack' })
        commit(types.COMMIT_ATTACK_CHARTS, { data: data.dataSource, type: 'auto' })
      } else if (status === 'fail') {
        // commit(types.COMMIT_LOADING_CHANGE, { val: false })
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 自动分析--获取攻击事件 表格信息
  */
  [types.GET_ATTACK_TABLEDATA] ({ commit, state }, obj) {
    commit(types.COMMIT_LOADING_CHANGE, { type: 'auto', val: true })
    if (obj.type === 'sorter') {
      commit(types.TABLE_SORTER_STATE_INIT, { type: 'AutoAttack', val: obj.val })
    } else if (obj.type === 'filter') {
      commit(types.TABLE_FILTER_STATE_INIT, { type: 'AutoAttack', val: obj.val })
    } else if (obj.type === 'pagSize') {
      commit(types.TABLE_PAGINATION_SIZE_STATE_INIT, { type: 'AutoAttack', val: obj.val })
    } else if (obj.type === 'pagCur') {
      commit(types.TABLE_PAGINATION_CURRENT_STATE_INIT, { type: 'AutoAttack', val: obj.val })
    }
    let args = new TableArgs(state, 'AutoAttack')
    $http.option('/api/analyze/autoAnalyze/getAttackTableDate', args).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_ATTACK_TABLEDATA, { data: data, type: 'AutoAttack' })
        commit(types.COMMIT_LOADING_CHANGE, { type: 'auto', val: false })
      } else if (status === 'fail') {
        commit(types.COMMIT_LOADING_CHANGE, { type: 'auto', val: false })
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 人工分析--获取攻击事件 统计信息
  */
  [types.GET_PER_ATTACK_STATISTICAL] ({ commit, state }) {
    $http.get('/api/analyze/Analyze/getPerAttackStatistical').then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_ATTACK_STATISTICAL, { data: data.dataSource, type: 'PerAttack' })
        commit(types.COMMIT_ATTACK_CHARTS, { data: data.dataSource, type: 'per' })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 人工分析--获取攻击事件 表格信息
  */
  [types.GET_PER_ATTACK_TABLEDATA] ({ commit, state }, obj) {
    commit(types.COMMIT_LOADING_CHANGE, { type: 'per', val: true })
    if (obj.type === 'sorter') {
      commit(types.TABLE_SORTER_STATE_INIT, { type: 'PerAttack', val: obj.val })
    } else if (obj.type === 'filter') {
      commit(types.TABLE_FILTER_STATE_INIT, { type: 'PerAttack', val: obj.val })
    } else if (obj.type === 'pagSize') {
      commit(types.TABLE_PAGINATION_SIZE_STATE_INIT, { type: 'PerAttack', val: obj.val })
    } else if (obj.type === 'pagCur') {
      commit(types.TABLE_PAGINATION_CURRENT_STATE_INIT, { type: 'PerAttack', val: obj.val })
    }
    let args = new TableArgs(state, 'PerAttack')
    $http.option('/api/analyze/analyze/getPerAttackTableDate', args).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_ATTACK_TABLEDATA, { data: data, type: 'PerAttack' })
        commit(types.COMMIT_LOADING_CHANGE, { type: 'per', val: false })
      } else if (status === 'fail') {
        commit(types.COMMIT_LOADING_CHANGE, { type: 'per', val: false })
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 获取规则配置信息
  */
  [types.GET_AUTO_RULES] ({ commit }) {
    $http.get('/api/analyze/autoAnalyze/getRuleConfig').then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_RULES_CONFIG_INIT, { data: data })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 新增自定义规则
  */
  [types.ADD_CUSTOM_RULE] ({ dispatch }, data) {
    $http.post('/api/analyze/autoAnalyze/addCustomRule', data).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        dispatch(types.GET_AUTO_RULES)
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 保存规则信息
  */
  [types.SAVE_RULES] ({ dispatch }, postData) {
    $http.option('/api/analyze/autoAnalyze/ruleSave', { dict: { ruleConfigs: postData.configs } }).then(({ status, msg } = {}) => {
      if (status === 'success') {
        if (postData.again === 'again') {
          dispatch(types.TRIGGER_ANALYZE)
        } else {
          dispatch(types.GET_ATTACK_STATISTICAL)
          dispatch(types.GET_ATTACK_TABLEDATA, { 'type': 'sorter', 'val': { 'field': 'astart_time', 'order': 'descend' } })
        }
        Notification.success('规则保存成功')
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 触发自动分析
  */
  [types.TRIGGER_ANALYZE] ({ dispatch }) {
    $http.get('/api/analyze/autoAnalyze/teigeerAnalyze').then(({ status, msg } = {}) => {
      if (status === 'success') {
        dispatch(types.GET_ATTACK_STATISTICAL)
        dispatch(types.GET_ATTACK_TABLEDATA, { 'type': 'sorter', 'val': { 'field': 'astart_time', 'order': 'descend' } })
        Notification.success('已完成自动分析')
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--事件信息与影响分析获取
   * @param {analyzeId} String - 分析编号
   * @param {attackEventId} String - 攻击事件编号
   * @param {analysisSource} String - 分析来源
  */
  [types.GET_DEPTH_ANALYSIS_EVENT_INFO] ({ commit, dispatch }, { registData, analyzeId, attackEventId, analysisSource }) {
    registData.depthAnalisisLoading = true
    let postData = {
      analyzeId: analyzeId,
      attackEventId: attackEventId,
      analysisSource: analysisSource
    }
    $http.post('/api/analyze/depthAnalyze/getDepthAnalysisEventInfo', postData).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_DEPTH_ANALYSIS_EVENT_INFO, { registData: registData, data: data })
        commit(types.COMMIT_DEPTH_ANALYSIS_STATISTICAL_CONCLUSION, { registData: registData })
        dispatch(types.GET_DEPTH_ANALYSIS_RELATED_INFO, { registData: registData, analyzeId: data.dataSource.analysis_id })
        registData.depthAnalisisLoading = false
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--相关风险信息
   * @param {analyzeId} String - 分析编号
  */
  [types.GET_DEPTH_ANALYSIS_RELATED_INFO] ({ commit }, { registData, analyzeId }) {
    registData.depthAnalisisLoading = true
    let postData = {
      analyzeId: analyzeId
    }
    $http.post('/api/analyze/depthAnalyze/getRelatedInfo', postData).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_DEPTH_ANALYSIS_EVENT_INFO, { registData: registData, data: data })
        registData.depthAnalisisLoading = false
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--添加要素--获取日志类型
  */
  [types.GET_LOG_TYPES] ({ commit }, { registData }) {
    $http.get('/api/analyze/depthAnalyze/getLogTypes').then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        registData.addElementTable.logFilterType = data.types
        registData.addElementTable.logFilterLevel = data.levels
        registData.addElementTable.logFilterBelongArea = data.belongArea
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--添加要素--获取日志
   * @param {elementType} String - 要素类型
   * @param {element} String - 要素名称
  */
  [types.GET_POTENTIAL_ADD_LOG] ({ state, commit }, { registData, elementType, element, issearch }) {
    registData.addElementTable.isLoading = true
    let esData = {
      'query': {
        'bool': {
          'must': [
          ]
        }
      },
      'sort': {
        'ts': {
          'order': 'desc'
        }
      }
    }
    if (elementType === '') {
      esData.query.bool.must.push({
        'query_string': {
          'query': element
        }
      })
    } else {
      let must = { 'match': {} }
      must.match[elementType] = element
      esData.query.bool.must.push(must)
    }
    // 时间
    if (registData.addElementTable.time) {
      let filter = [
        {
          'range': {
            'ts': {
              'gte': registData.addElementTable.time.split(' - ')[0],
              'lte': registData.addElementTable.time.split(' - ')[1]
            }
          }
        }
      ]
      esData.query.bool.filter = filter
    }
    if (issearch === 'table') {
      // filter过滤
      if (registData.addElementTable.filter) {
        for (let [key, value] of Object.entries(registData.addElementTable.filter)) {
          if (value.length > 0) {
            let must = { 'bool': { 'should': [] } }
            for (let index in value) {
              let should = { 'match': {} }
              should.match[key] = value[index]
              must.bool.should.push(should)
            }
            esData.query.bool.must.push(must)
          }
        }
      }
      // 模糊搜索
      if (registData.addElementTable.search) {
        let must = {
          'bool': {
            'should': [
            ]
          }
        }
        let search = ['url', 'malname', 'vul_name', 'behavior', 'cve_id']
        for (let i in search) {
          let should = { 'wildcard': {} }
          should.wildcard[search[i]] = `*${registData.addElementTable.search}*`
          must.bool.should.push(should)
        }
        esData.query.bool.must.push(must)
      }
      // 筛选条件--模糊搜索
      if (registData.addElementTable.accurateSearch) {
        let must = {
          'bool': {
            'must': [
            ]
          }
        }
        for (let [key, value] of Object.entries(registData.addElementTable.accurateSearch)) {
          if (value) {
            let wMust = { 'wildcard': {} }
            wMust.wildcard[key] = `*${value}*`
            must.bool.must.push(wMust)
          }
        }
        esData.query.bool.must.push(must)
      }
    }
    state.esData = JSON.stringify(esData)
    esData.from = (registData.addElementTable.current - 1) * registData.addElementTable.pageSize
    esData.size = registData.addElementTable.pageSize
    let postData = {
      elementType: elementType,
      element: element,
      esData: JSON.stringify(esData)
    }
    $http.post('/api/analyze/depthAnalyze/getPotentialAddLog', postData).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_GET_POTENTIAL_LOG, { registData: registData, data: data })
        registData.addElementTable.isLoading = false
        if (issearch === 'table') {
          registData.addElementTable.showHearder = true
        } else {
          if (data.esData.hits.total > 0) {
            registData.addElementTable.showHearder = true
          } else {
            registData.addElementTable.showHearder = false
          }
        }
        // commit(types.COMMIT_SAVE_ANALYSIS, { registData: registData, data: data })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--添加要素--获取选中的日志
   * @param {analyzeId} String - 分析编号
   * @param {element} String - 要素名称
   * @param {elementStep} String - 要素来源步骤
  */
  [types.GET_CHECKED_LOG] ({ state, commit }, { analyzeId, element, elementStep }) {
    state.checkedLogData.allocation.dict = {
      analyzeId: analyzeId,
      element: element,
      elementStep: elementStep
    }
    state.checkedLogData.isLoading = true
    $http.option('/api/analyze/depthAnalyze/getCheckedLog', state.checkedLogData.allocation).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        commit(types.COMMIT_GET_CHECKED_LOG, { data: data })
        state.checkedLogData.isLoading = false
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--删除要素
   * @param {analyzeId} String - 分析编号
   * @param {element} String - 要素名称
   * @param {elementStep} String - 要素来源步骤
  */
  [types.DEL_ELEMENT] ({ dispatch }, { registData, analyzeId, element, elementStep }) {
    let postData = {
      analyzeId: analyzeId,
      element: element,
      elementStep: elementStep
    }
    $http.post('/api/analyze/depthAnalyze/delElement', postData).then(({ status, msg } = {}) => {
      if (status === 'success') {
        Notification.success('删除成功')
        dispatch(types.GET_DEPTH_ANALYSIS_EVENT_INFO, { registData: registData, analyzeId: analyzeId })
        // commit(types.COMMIT_SAVE_ANALYSIS, { registData: registData, data: data })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--删除相关信息或日志
   * @param {id} String - 记录编号
   * @param {elementId} String - 要素编号
  */
  [types.DEL_RELATED_OR_LOG] ({ dispatch }, { registData, id, elementId, analyzeId, element, elementStep }) {
    let postData = {
      id: id,
      elementId: elementId
    }
    $http.post('/api/analyze/depthAnalyze/delRelatedOrLog', postData).then(({ status, msg } = {}) => {
      if (status === 'success') {
        Notification.success('删除成功')
        if (elementId !== '0') {
          // 删除内容为日志信息
          dispatch(types.GET_CHECKED_LOG, { analyzeId: analyzeId, element: element, elementStep: elementStep })
        }
        dispatch(types.GET_DEPTH_ANALYSIS_EVENT_INFO, { registData: registData, analyzeId: analyzeId })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  },
  /**
   * @description 深度分析--添加要素--确认添加要素
   * @param {analyzeId} String - 分析编号
   * @param {element} String - 要素名称
   * @param {elementStep} String - 要素来源步骤
   * @param {attackEventId} String - 事件id回调使用
  */
  [types.CONFIRM_ADD_ELEMENT] ({ state, dispatch }, { registData, analyzeId, type, keyword, elementStep, checkedAll, logs, checkedElement }) {
    let postData = {
      analyzeId: analyzeId,
      type: type,
      keyword: keyword,
      elementStep: elementStep, // 影响与潜在影响
      checkedAll: checkedAll, // 是否勾选全部
      logs: logs,
      checkedElement: checkedElement,
      esData: state.esData
    }
    $http.post('/api/analyze/depthAnalyze/confirmAddElement', postData).then(({ status, msg, data } = {}) => {
      if (status === 'success') {
        Notification.success('添加成功')
        dispatch(types.GET_CHECKED_LOG, { analyzeId: analyzeId, element: keyword, elementStep: elementStep })
        dispatch(types.GET_DEPTH_ANALYSIS_EVENT_INFO, { registData: registData, analyzeId: analyzeId })
      } else if (status === 'fail') {
        Notification.warning(msg)
      }
    })
  }
}

export default actions
